#include <QApplication>
#include <QSplashScreen>
#include <QString>

#include "mainwindow.h"
#include "mannasettings.h"
#include "externtool.h"
#include "helpwidget.h"

#ifdef Q_OS_WIN
    #define WIN32_MEAN_AND_LEAN
    #include <windows.h>
    #include <winuser.h>
    #include <unistd.h>
    #include <tlhelp32.h>
    #undef CONST    // conflict with CONST in MIValueType
    #undef ERROR
#else
    #include <sys/types.h>
    #include <sys/stat.h>
    #include "misc.h"
#endif

int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN //set only one case can be running.
    HANDLE hMutex = CreateMutex(NULL, true, QString("GUIDE_201005_APP_WIN").toStdWString().c_str());
    if (GetLastError() == ERROR_ALREADY_EXISTS) {
        CloseHandle(hMutex);
        QString lpszParentWindow = "GUIDE";
        HWND ParenthWnd;
        LPTSTR windowName;
        windowName = new TCHAR[lpszParentWindow.length() + 1];
    #ifdef UNICODE
        *(windowName + lpszParentWindow.toWCharArray(windowName)) = 0;
    #else
        strcpy(windowName, lpszParentWindow.toLatin1().constData());
    #endif
        int clock = 200;
        while ( clock > 0) {
            ParenthWnd = FindWindow(NULL, windowName);
            if (ParenthWnd) break;
            Sleep(50);
            --clock;
        }
        if (ParenthWnd) {
            char tmp[512];
            memset(tmp,0,512*sizeof(char));
            for (int i = 1; i < argc; ++i) {
                //qDebug("already one!");
                strcpy(tmp, argv[i]);
                COPYDATASTRUCT cpd;
                cpd.dwData = 0;
                cpd.cbData = strlen(tmp);
                cpd.lpData = (void*)tmp;
                ::SendMessage(ParenthWnd, WM_COPYDATA, 0, (LPARAM)&cpd);
                qDebug("Open %s", argv[i]);
            }
        }
        return 0;
    }
#else
    QString path = getMannaPath();
    path += "GUIDE.lock";
    int lock_file = open(path.toLocal8Bit().constData(), O_RDWR | O_CREAT,S_IRWXU);
    struct flock arg;
    arg.l_type = F_WRLCK;
    arg.l_whence = 0;
    arg.l_start = 0;
    arg.l_len = 0;
    if (fcntl(lock_file,F_SETLK,&arg) == -1) {
        int fd;
        char buffer[FILE_MAXLENGTH+1];
        path = getMannaPath();
        path += "comm";
        mkfifo(path.toLatin1().constData(),S_IFIFO|0666);
        if ((fd = open(path.toLatin1().constData(),O_WRONLY ,0)) == -1 ) {
            qDebug("failed!");
            return 0;
        }
        for (int i = 1;i < argc;++i) {
            if (strlen(argv[i]) > FILE_MAXLENGTH) {
                continue;//if a filename is too long,not dealed.
            }
            strcpy(buffer,argv[i]);
            //buffer[strlen(buffer)] = '\n';
            write(fd,buffer,strlen(buffer));
        }
        close(fd);
        return 0;
    }
    // Set locale to let output of gcc/g++ to be english under Unix-like OS.
    setLocaleToC();
#endif

    Q_INIT_RESOURCE(Manna);
    QApplication app(argc, argv);

    MannaSettings::setIniInformations();

    QColor msgclr = QColor(255,255,255);

    QSplashScreen *splash = new QSplashScreen(QPixmap(":/logo/images/application/splash.png"));
    splash->setFont( QFont("Helvetica", 10) );
    splash->show();

    QTranslator mt;
    QTranslator qt;
    mt.load(":/translations/lang_zh_CN");
    qt.load(":/translations/qt_zh_CN");
    qApp->installTranslator(&mt);
    qApp->installTranslator(&qt);

    splash->showMessage(QObject::tr("Loading..."),
        Qt::AlignRight | Qt::AlignBottom, msgclr);
    qApp->processEvents();
    MannaSettings::getMannaSettings()->prepareAPIs();

    splash->showMessage(QObject::tr("Checking external tools..."),
        Qt::AlignRight | Qt::AlignBottom, msgclr);
    qApp->processEvents();

    QString externtool_show = "";
    MannaSettings *settings = MannaSettings::getMannaSettings();
    settings->beginGroup("ExternTools");
    externtool_show = settings->value("show_flag","false").toString();
    settings->endGroup();

    if (externtool_show == "false") {
        ExternTool::checkExternTool();
    } else {
        ExternTool::setEnvironment();
    }

    qApp->removeTranslator(&mt);
    qApp->removeTranslator(&qt);

    HelpWidget::iniCHelpNames();
    HelpWidget::iniPasHelpNames();

    MainWindow mainWin;

    splash->showMessage(QObject::tr("Main Window creation"),
        Qt::AlignRight | Qt::AlignBottom, msgclr);
    qApp->processEvents();
    mainWin.show();

    splash->finish(&mainWin);
    delete splash;
    splash = 0;

    return app.exec();
}
